# -*- coding:utf-8 -*-
__author__ = 'stevezhou'

import marshal
import anydbm
import time

import os
import logging

_logger = logging.getLogger(__name__)

class Token_FileCash():
    def __init__(self, corpid='wechat_access_token'):
        self.corpid = corpid
        self.base_path = os.path.expanduser("~")+"/opt/isleep/wechat/token"
        os.system('mkdir -p %s'%self.base_path)
        self.file_path = "%s/%s"% (self.base_path,self.corpid )
        _logger.info("tokent file path:%s"% self.file_path)

    def cash_write(self, tokendict):
        dbmOut = anydbm.open(self.file_path, 'n')
        dbmOut['token']=marshal.dumps(tokendict['token'])
        dbmOut['js_ticket']=marshal.dumps(tokendict['js_ticket'])
        dbmOut['expired']=marshal.dumps(tokendict['expired'])
        dbmOut['gettime']=marshal.dumps(tokendict['gettime'])
        dbmOut.close()


    def cash_read(self):
        try:
            dbmIn = anydbm.open(self.file_path)
            js_ticket = marshal.loads(dbmIn['js_ticket'])
            token = marshal.loads(dbmIn['token'])
            expired = marshal.loads(dbmIn['expired'])
            gettime = marshal.loads(dbmIn['gettime'])
        except:
            # print "file not found"
            return None
        else:
            # print token, str(expired), str(gettime)
            return {'token': token, 'js_ticket': js_ticket, 'expired': expired, 'gettime': gettime}

    def validExpired(self, tokendict):
        now_second = time.time()
        if now_second - tokendict['gettime'] > tokendict['expired']:
            return False
        else:
            return True


    def validToken(self):
        tokendict = self.cash_read()
        if tokendict:
            return self.validExpired(tokendict), tokendict
        else:
            return False, None



# print 'write file'
# cash_write({'token': 'fsdfdsdasda', 'expired': 7200, 'gettime': 42242452232})
#
# print 'read file'
# print cash_read()
